package com.dq.utils;

import com.dq.exception.customException.AdminException;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.exception.QRGenerationException;
import net.glxn.qrgen.image.ImageType;


/**
 * 二维码
 * @author cr
 */
public class QrUtils {

    /**
     * url - > 二维码 InputStream
     * @param qrUrl 二维码 url
     * @param width 二维码 宽度, 有默认值
     * @param height 二维码 高度, 有默认值
     * @return 二维码 InputStream
     */
    public static InputStream makeQrCode(String qrUrl, Integer width, Integer height) {
        if(StringUtils.isBlank(qrUrl)) {
            throw new AdminException("需转化的二维码URL为空");
        }

        width = (width == null ? 250 : width);
        height = (height == null ? 250 : height);

        try {
            QRCode qrCode = QRCode.from(qrUrl)
                    // 定义二维码的参数
                    .to(ImageType.JPG)
                    .withSize(width, height)
                    .withHint(EncodeHintType.CHARACTER_SET, "utf-8")
                    .withHint(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H)
                    .withHint(EncodeHintType.MARGIN, 2);
            // 生成二维码 InputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            qrCode.writeTo(baos);

            return new ByteArrayInputStream(baos.toByteArray());
        } catch (QRGenerationException e) {
            e.printStackTrace();
            throw new AdminException("[url -> 二维码 InputStream 异常] msg: " + e.getMessage());
        }
    }

}
